package com.xiao.springmvc.controller.product;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiao.springmvc.entity.ProductImage;
import com.xiao.springmvc.entity.ProductInfo;
import com.xiao.springmvc.entity.jdo.ProductGetJdo;
import com.xiao.springmvc.service.ProductImageService;
import com.xiao.springmvc.service.ProductService;
import com.xiao.springmvc.util.PageJsonUtil;

@Controller
@RequestMapping(value="/product")
public class ProductController {

	@Autowired
	private ProductService productService;
	@Autowired
	private ProductImageService productImageService;
	
	@RequestMapping(value="get",method=RequestMethod.GET)
	@ResponseBody
	public Object get(
			@RequestParam(value="pageNo",defaultValue="0") int pageNo,
			@RequestParam(value="companyId") Long companyId, ServletRequest request
			){
		int pageSize = 10;
		Pageable pageable = new PageRequest(pageNo, pageSize);
		Page<ProductInfo> productInfoPage = productService.findByCompanyId(companyId, pageable);
		List<ProductInfo> productInfoList = productInfoPage.getContent();
		List<ProductGetJdo> jdoList = new ArrayList<ProductGetJdo>();
		long total = productInfoPage.getTotalElements();
		
		for(ProductInfo p : productInfoList){
			ProductImage image = productImageService.findByProductIdAndOrderId(p.getId(), 0);
			ProductGetJdo jdo = new ProductGetJdo();
			jdo.setProductId(p.getId());
			jdo.setProductName(p.getName());
			jdo.setProductIntroduce(p.getIntroduce());
			jdo.setProductPicture(image.getFilepath());
			jdoList.add(jdo);
		}
		
		PageJsonUtil<ProductGetJdo> data = new PageJsonUtil<ProductGetJdo>(
				pageNo,total,jdoList
				);
		return data;
	}
	
	@RequestMapping(value="show",method=RequestMethod.GET)
	@ResponseBody
	public Object show(
			@RequestParam(value="productId") Long productId, ServletRequest request
			){
		Object data = null;
		
		ProductInfo product = productService.findById(productId);
		List<ProductImage> imageList = productImageService.findByProductId(productId);
		
		ProductJson json = new ProductJson();
		data = json.productShowJson(product, imageList);
		
		return data;
	}
}
